/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import java.io.DataInputStream;
import java.io.PrintStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;

public class DataTransfer implements Runnable {

    public static DataTransfer dataTransfer;
    private String serverHost = "210.211.127.164";
    private String serverPort = "6666";
    private String connectString1 = "socket://porker1.inet.vn:6666";
    private String connectString2 = "socket://porker2.inet.vn:6666";
//    private String connectString1 = "sockset://localhost:9000";
//    private String domain = "Poker1.inet.vn";
    private MasterServer masterServer;
    private boolean isConnect = true;
    private boolean isRunning;
    public Vector dataInputQueue;
    private IMessageListenner messageListenner;
    private PrintStream dataOutputStream;
    private DataInputStream dataInputStream;
    private ReaderThread reader;
    private SocketConnection socket;

    private DataTransfer() {
        Debug.d("new datatranfer");
        masterServer = new MasterServer(serverHost, serverPort);
        SlaveInfo slaveInfo = masterServer.getServerInfo();
        this.serverHost = slaveInfo.serverHost;
        this.serverPort = slaveInfo.serverPort;
        isConnect = createConnection(0);
        if (!isConnect) {
            isConnect = createConnection(1);
        }
    }

    public static DataTransfer getInstance() {
        if (dataTransfer == null) {
            dataTransfer = new DataTransfer();
        }
        return dataTransfer;
    }

    public void setMessageListenner(IMessageListenner messageLinner) {
        this.messageListenner = messageLinner;
        if (!isConnect) {
            dataTransfer = null;
        }
    }

    public boolean isConnect() {
        return this.isConnect;
    }

    private boolean createConnection(int type) {
        try {
//            String url = "socket://" + serverHost + ":" + serverPort;
//            socket = (SocketConnection) Connector.open(url);
            if (type == 0) {
                socket = (SocketConnection) Connector.open(connectString1);
            } else {
                socket = (SocketConnection) Connector.open(connectString2);
            }
            socket.setSocketOption(socket.RCVBUF, 16384);
            dataInputQueue = new Vector();
            dataOutputStream = new PrintStream(socket.openOutputStream());
            dataInputStream = new DataInputStream(socket.openInputStream());
            startThread();
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            Debug.d("connect failed");
            return false;
        }
    }

    private void startThread() {
        reader = new ReaderThread(dataInputStream, this);
        isRunning = true;
        new Thread(this).start();
    }

    public void request(String message) {
        Debug.d("send :" + message);
        try {
            byte[] outMsg = null;
            int dataLength = message.getBytes("UTF-8").length + 2;
//            Debug.d("data length :" + dataLength);
            outMsg = new byte[dataLength];
            System.arraycopy(message.getBytes("UTF-8"), 0, outMsg, 1, dataLength - 2);
            outMsg[0] = 125;
            outMsg[dataLength - 1] = 38;
            dataOutputStream.write(outMsg);
            dataOutputStream.flush();
        } catch (Exception ex) {
        }
    }

    public void run() {
        while (isRunning) {
            if (dataInputQueue.size() > 0 && isConnect) {
                String message = (String) dataInputQueue.elementAt(0);
                Debug.d("Receive:" + message);
                String[] part = StringHelper.split(message, '|');
                messageListenner.processMessage(part);
                dataInputQueue.removeElementAt(0);
            }
            try {
                Thread.sleep(10);
            } catch (InterruptedException ex) {
            }
        }
    }

    public void quit() {
        String[] part = {"QUIT"};
        messageListenner.processMessage(part);
    }

    public void stop() {
        try {
            isConnect = false;
            isRunning = false;
            reader.stop();
            socket.close();
            dataInputStream.close();
            dataOutputStream.close();
            quit();
        } catch (Exception ex) {
        }
    }

    public static void releaseConnection() {
        if (dataTransfer != null) {
            dataTransfer.stop();
        }
        dataTransfer = null;
        Runtime.getRuntime().gc();
    }
}
